<template>
  <div>
    <el-dialog title="导入打款批次" :model-value="props.modelValue" width="800px"  @open="onLineOpen" @close="$emit('update:modelValue', false)"  :close-on-click-modal="false">
      <el-form :model="paymentModalFormData" :rules="rules" ref="formRef"  label-suffix=":" label-width="150">
        <el-form-item label="业务类型" prop="busType">
          <el-select style="width: 100%" placeholder="请选择业务类型" v-model="paymentModalFormData.busType">
            <el-option v-for="item in businessTypeOptions1" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目选择" prop="taskId">
          <el-select style="width: 100%" placeholder="请选择项目" v-model="paymentModalFormData.taskId" @change="selectTask">
            <el-option v-for="item in projectOptions" :key="item.id" :label="'【'+item.no+'】'+item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="产品选择" prop="proId">
          <el-select style="width: 100%" placeholder="请选择产品" v-model="paymentModalFormData.id"  @change="selectPro">
            <el-option v-for="item in merchantOptions" :key="item.id" :label="getProInfo(item)" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item  v-if="showProDetail">
          <template #label>
            <span style="width: 4rem;"></span>
          </template>
          <div class="product-detail">
            <el-descriptions :column="1">
              <template #title>
                <div class="product-detail__title">
                  <img width="20" src="@/assets/logo/ticket.png" alt="" />
                  <span>
                    {{`产品编号:${projectDetails?.proNo || ''}`}}
                  </span>
                </div>
              </template>
              <el-descriptions-item label="服务费率:"><span style="font-weight: 700;">{{projectDetails?.serviceCharge}}% </span></el-descriptions-item>
              <el-descriptions-item label="产品限额:"><span style="font-weight: 700;">{{proxy.convertFenToYuan(projectDetails?.maxMonth) || ''}} </span></el-descriptions-item>
              <!-- 1:个人应得计费、2:开票金额计费 -->
              <el-descriptions-item label="计费模式:" :span="2"><span style="font-weight: 700;">{{
                  projectDetails?.chargeMode === 1 ? '个人应得计费' :  projectDetails?.chargeMode === 2 ? '开票金额计费' : ''
              }} </span></el-descriptions-item>
              <!-- 结算方式（1：到卡 2：余额） -->
              <el-descriptions-item label="到账方式:">
                <span style="font-weight: 700;">{{projectDetails?.settlementStyle === 1 ? '到卡' : projectDetails?.settlementStyle === 2 ? '余额' : ''}} </span>
              </el-descriptions-item>
              <el-descriptions-item label="开票项目:">
                {{projectDetails?.invoiceItems}}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-form-item>

        <el-form-item label="服务费承担方" prop="serviceChargeType">
          <el-radio-group style="width: 100%" v-model="paymentModalFormData.serviceChargeType">
            <el-radio :label="1">用工企业承担</el-radio>
            <el-radio :label="2">自由职业者承担</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="上传批量打款文件"  >
          <el-upload
             ref="fileUploadRef"
            :headers="headers"
            :data="uploadData"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
            :on-success="handleUploadSuccess"
            :on-exceed="handleExceed"
            :file-list="fileList"
            class="upload-file-uploader"
            :show-file-list="false"
            :action="uploadFileUrl"
            :limit="1"
          >
            <el-button type="primary">上传批量打款文件</el-button>
            <template #tip>
              <div class="el-upload__tip">大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>,格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>.</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
         <!-- <el-button @click="upload" type="primary">上传</el-button> -->
          <el-button @click="$emit('update:modelValue', false)">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import moment from 'moment';
import type { FormInstance, FormRules } from 'element-plus'
import useUserStore from '@/store/modules/user'
import type { UploadUserFile } from 'element-plus'
import { globalHeaders } from "@/utils/request";

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const {invoice_type} = toRefs(proxy?.useDict("invoice_type"));
const fileSize = ref(5);
const fileType = ref(["xlsx"]);
const fileList = ref<UploadUserFile[]>([])
const number = ref(0);

  const showProDetail = ref(false)
  const projectOptions = ref([])
  const merchantOptions = ref([])
  const emit = defineEmits(['update:modelValue', 'onSuccess'])
  const projectDetails = ref({});
  const formRef = ref<FormInstance>()
  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  const uploadFileUrl = ref(baseUrl + "/payment/bill/importBillData"); // 上传文件服务器地址
  // const uploadFileUrl = ref(baseUrl + "/resource/oss/upload"); // 上传文件服务器地址

  const businessTypeOptions1 = ref([]);

  const paymentModalFormData = reactive({
    no: '',
    busType: '',
    taskId: '',
    taskNo: '',
    proId: '',
    proNo: '',
    serviceChargeType: 1, // 1:用工企业承担 2:自由职业者承担
  })

  const uploadData = ref({});

  const onLineOpen = ()=>{
      formRef.value?.resetFields();
      fileList.value = [];
      showProDetail.value = false;

  }

const headers = ref(globalHeaders());

const selectPro = (val:any)=>{

    let moList = merchantOptions.value;
    let size = moList.length;
    let selObj = null;
    for(let i = 0 ; i < size;i++){
        if(moList[i].id == val){
          selObj = moList[i];
          break;
        }
    }

    showProDetail.value = true;
    projectDetails.value = selObj;


}

const selTask = ref({});

//选择任务
const selectTask = (val:any)=>{
    let pvList = projectOptions.value;
    let size = pvList.length;
    for(let i = 0 ; i < size ; i++){
        if(pvList[i].id == val){
          selTask.value = pvList[i];
          break;
        }
    }

}



// 上传前校检格式和大小
const handleBeforeUpload = async(file: any) => {
      const data = await  formRef.value?.validate();
      if(!data){
        return false;
      }
    // 校检文件类型
    if (fileType.value.length) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = fileType.value.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
            proxy?.$modal.msgError(`文件格式不正确, 请上传${fileType.value.join("/")}格式文件!`);
            return false;
        }
    }
    // 校检文件大小
    if (fileSize.value) {
        const isLt = file.size / 1024 / 1024 < fileSize.value;
        if (!isLt) {
            proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize.value} MB!`);
            return false;
        }
    }
    let defaultProvider = useUserStore().defaultProvider;
    uploadData.value = {
        ...paymentModalFormData,
        maxMonth: projectDetails.value.maxMonth,
        proId: projectDetails.value.proId,
        chargeMode: projectDetails.value.chargeMode,
        merId: defaultProvider.merId,
        sydNo: defaultProvider.sydNo,
        invoiceType: projectDetails.value.invoiceType,
        channelCode: projectDetails.value.channelCode,
        proNo: projectDetails.value.proNo,
        merNo: defaultProvider.merNo,
        taskId: selTask.value.id,
        taskNo: selTask.value.no,
        settlementStyle: projectDetails.value.settlementStyle,
        sydId: defaultProvider.sydId,
        sydNo:defaultProvider.sydNo,
        passage:defaultProvider.bankType,
        domain: location.origin,
        serviceChargeRate: projectDetails.value.serviceCharge,
    }
    proxy?.$modal.loading("正在上传文件，请稍候...");
    number.value++;
    return true;
}


// 文件个数超出
const handleExceed = () => {
    proxy?.$modal.msgError(`上传文件数量不能超过1个!`);
}

// 上传失败
const handleUploadError = () => {
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgError("上传文件失败");
}

// 上传结束处理
const uploadedSuccessfully = () => {
    // if (number.value > 0 && uploadList.value.length === number.value) {
    //     fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
    //     uploadList.value = [];
    //     number.value = 0;
    //     emit("update:modelValue", listToString(fileList.value));
    //     proxy?.$modal.closeLoading();
    // }
}

const fileUploadRef = ref();


// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
    if (res.code === 200) {
        // uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
        const {list,errorList,analysis,allRecords} = res.data;
        proxy?.$modal.closeLoading();
        emit('update:modelValue', false);
        emit('onSuccess', {
          code: 200,
          success: errorList.length> 0 ?false:true,
          allRecords:allRecords,
          params:uploadData.value,
          analysis:analysis,
          msg: '操作成功',
          data: {
            list: list,
            errorList: errorList,
            analysis: 'analysis',
          }
        })



        uploadedSuccessfully();
    } else {
        number.value--;
        proxy?.$modal.closeLoading();
        proxy?.$modal.msgError(res.msg);
        fileUploadRef.value?.handleRemove(file);
        uploadedSuccessfully();
    }
}





  const upload = () => {
    const formData = new FormData()
    formData.append('file', fileList.value[0]?.raw)
    Object.entries(paymentModalFormData).forEach(([key, value]) => {
      formData.append(key, value)
    });
    useRequest('/payment/bill/importBillData', 'POST', {
      data: formData
    }, { immediate: true,
      onFinish: () => {

        emit('onSuccess', {
                code: 200,
                success: Math.random() > 0.5,
                msg: '操作成功',
                data: {
                  list: [
                    { moneyDecimal: '998', billIds: 'billIds', amount: 99878, money: 'money', serviceChargeMoney: '78' },
                  ],
                  errorList: [{ name: '张三', cardId: '411589245741568841', money: 9999, memo: '身份证ID有误'}],
                  analysis: 'analysis',
                }
              })
      }
    })
  }



  const rules = reactive<FormRules<RuleForm>>({
  no: [
    { required: true, message: "批次号不能为空", trigger: 'change' },
  ],
  busType: [
    {
      required: true,
      message: "业务类型不能为空",
      trigger: 'change',
    },
  ],
  serviceChargeType: [
    {
      required: true,
       message: "服务费承担方不能为空",
      trigger: 'change',
    },
  ],
  taskId: [
    {
      required: true,
      message: "项目不能为空",
      trigger: 'change',
    },
  ],
  id: [
    {
      required: true,
       message: "产品不能为空",
      trigger: 'change',
    },
  ],
  })


  watch(() => paymentModalFormData.busType, async (busType) => {
    if(!busType){
      return;
    }
    paymentModalFormData.taskId = ''
    paymentModalFormData.proId = ''
  let defaultProvider = useUserStore().defaultProvider;

    const { data } = await useRequest('/payment/task/queryList', 'GET', {
    params: { busType, sydId: defaultProvider.sydId,status:1,taskStatus:7,classify:1 }
    }, { immediate: true })


    if (data) {
      projectOptions.value = data.value
    }

    const { data: merchantList } = await useRequest('/payment/merchantProduct/queryList', 'GET', {
    params: { busType, sydId: defaultProvider.sydId }
    }, { immediate: true })
    if (merchantList) {
      merchantOptions.value = merchantList.value
    }
  })

  const getInvoiceType = (val)=>{
    return proxy?.getDicValue(val,invoice_type.value);
  }



  const getProInfo = (item:any)=>{
     let chargeMode = item?.chargeMode === 1 ? '个人应得计费' :  item?.chargeMode === 2 ? '开票金额计费' : ''
      return item.proNo +"-"+getInvoiceType(item.invoiceType)+"-"+chargeMode+"-"+ item.serviceCharge+"%";
  }


  const props = defineProps({
      modelValue: {
          type: Boolean
      },
      businessTypeOptions: {},
  });

  watch(() => props.businessTypeOptions, async (val) => {
     businessTypeOptions1.value = val;
  });
</script>

<style scoped lang="scss">

:deep(.el-descriptions__body .el-descriptions__table:not(.is-bordered) .el-descriptions__cell) {
       padding-bottom: 2px;
  }


.product-detail {
  padding: 15px;
  border: 1px solid #ddd;
  width: 100%;
  max-height: 280px;
  overflow: auto;
  background-color: rgb(249, 249, 249);
  border-radius: 5px;
  :deep(.el-descriptions__body) {
    background-color: rgb(249, 249, 249);
  }

  :deep(.product-detail__title){
    border-bottom:  1px solid #ddd;
    width: 600px;
    display: flex;
    align-items: center;
    img {
      display: block;
      margin-right: 15px;
    }
  }
}
</style>
